package config

import (
	"cgs-server/internal/cgserver/embedfile"
	"net/http"

	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/system"
	"go.mongodb.org/mongo-driver/bson"
)

func init() {
	//server.Handle(http.MethodGet, "/api/Config/Get", Get, server.None)
	server.Get("/api/Config/Get", Get, "获取配置信息", server.None)
	server.Get("/api/Config/Sys/Get", getConfig, "获取配置信息", server.None)
}

// Get get the server config of the current user.
func Get(w http.ResponseWriter, r *http.Request) {
	db, err := server.Mongo()
	if err != nil {
		helper.Write(w, err.Error())
		return
	}

	config := system.Config{}
	filter := bson.M{
		"type": bson.M{
			"$exists": false,
		},
	}
	find, err := db.FindOne(server.ConfigCollectionName, filter, &config)
	if err != nil {
		helper.WriteJSON(w, server.Result{
			Code: 300,
			Msg:  err.Error(),
		})
		return
	}

	if !find {
		/*doc1 := bson.M{
			"ID":                  primitive.NewObjectID().Hex(),
			"Initialized":         false,
			"DefaultRegisterRole": "",
		}
		db.InsertOne(server.ConfigCollectionName, doc1)
		db.FindOne(server.ConfigCollectionName, bson.M{}, &config)*/
		config = system.Config{
			ID:                  "",
			Initialized:         false,
			DefaultRegisterRole: "",
		}
	}

	result := Result{
		ID:                   config.ID,
		EnableAuthority:      server.Config.Authority.Enabled,
		Initialized:          config.Initialized,
		DefaultRegisterRole:  config.DefaultRegisterRole,
		IsLogin:              false,
		Username:             "",
		Name:                 "",
		RoleID:               "",
		RoleName:             "",
		DeptID:               "",
		DeptName:             "",
		OperatingAuthorities: []string{},
		EnableRemoteEdit:     server.Config.Remote.Enabled,
		WebSocketServerPort:  server.Config.Remote.WebSocketPort,
	}

	user, _ := server.GetCurrentUser(r)

	if user != nil {
		result.IsLogin = true
		result.Username = user.Username
		result.Name = user.Name
		result.RoleID = user.RoleID
		result.RoleName = user.RoleName
		result.DeptID = user.DeptID
		result.DeptName = user.DeptName
		result.OperatingAuthorities = user.OperatingAuthorities
	}

	helper.WriteJSON(w, server.OK("Get Successfully!").WithData(result))
}

// Result config to front end
type Result struct {
	// ID
	ID string `json:"id"`
	// Enable Authority
	EnableAuthority bool `json:"enableAuthority"`
	// Has Initialized
	Initialized bool `json:"initialized"`
	// Default Register Role
	DefaultRegisterRole string `json:"defaultRegisterRole"`
	// Is Login
	IsLogin bool `json:"isLogin"`
	// Username
	Username string `json:"username"`
	// Name
	Name string `json:"name"`
	// Role ID
	RoleID string `json:"roleID"`
	// Role Name
	RoleName string `json:"roleName"`
	// Department ID
	DeptID string `json:"deptID"`
	// Department Name
	DeptName string `json:"deptName"`
	// Operating Authorities
	OperatingAuthorities []string `json:"operatingAuthorities"`
	// Enable Remote Edit
	EnableRemoteEdit bool `json:"enableRemoteEdit"`
	// Web Socket Server Port
	WebSocketServerPort int `json:"webSocketServerPort"`
}

func getConfig(w http.ResponseWriter, r *http.Request) {

	db, err := server.Mongo()
	if err != nil {
		helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	var res = SystemConfig{}
	find, _ := db.FindOne(server.ConfigCollectionName, bson.M{"type": "system"}, &res)

	if find {

	} else {
		res.Type = "system"
		_, err = db.InsertOne(server.ConfigCollectionName, res)
	}

	if err != nil {
		helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	if res.Logo == "" {
		//res.Logo = "static/img/logo.png"
		res.Logo = embedfile.LogoBase64
	}

	helper.WriteJSON(w, server.OK("Get successfully!").WithData(res))
}
